<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

session_start();

class Main extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
            if(!$this->logged_in()){
                $this->load->view('login');
            }
            else{   
                $api_key = $this->generate_guid(31);
                $this->load->model('Main_model');
                $user_mail = $_SESSION['email'];
                $update_user_api_key = $this->Main_model->update_api_key($user_mail, $api_key);
                $user_api_key = $this->Main_model->get_user_api_key($user_mail);
                $data['api_key'] = $user_api_key;
                $data['title'] = 'scraper.mk';
                $data['kt_script'] = $this->get_script_code($user_api_key);
                $this->load->view('main', $data);
            }
	}
        
        public function logged_in(){
            if(isset($_SESSION['user']) and isset($_SESSION['email']))
                return true;
            else
                return false;
        }
        
        public function logout(){
            unset($_SESSION['user']);
            unset($_SESSION['email']);
            session_destroy();
            header("Location: " . base_url());
        }
        
        public function login(){
            if(isset($_POST)){
                if(isset($_POST['email']) and isset($_POST['password'])){
                    $email = $_POST['email'];
                    $password = $_POST['password'];
                    
                    $this->load->model('Main_model');
                    $password = md5($password);
                    $user_exist = $this->Main_model->user_exist($email, $password);
                    if($user_exist){
                        if(!isset($_SESSION['user'])){
                            $_SESSION['user'] = $this->Main_model->get_name($email);
                            $_SESSION['email'] = $email;
                        }
                        echo '1';
                    }
                    else
                        echo 'Login not succeded !';
                }
            }
        }
        
        public function register(){
            if(isset($_POST)){
                if(isset($_POST['name']) and isset($_POST['email']) and isset($_POST['password'])){
                    $name = $_POST['name'];
                    $email = $_POST['email'];
                    $password = $_POST['password'];

                    if($this->validate('name', $name)){
                            if($this->validate('email', $email)){
                                if($this->validate('password', $password)){
                                    $this->load->model('Main_model');
                                    $password = md5($password);
                                    $query = $this->Main_model->register($name, $email, $password);
                                    if($query)
                                        echo 'Registration successful';
                                }
                                else
                                    echo $_SESSION['message'][2];
                            }
                            else
                                echo $_SESSION['message'][1];
                    }
                    else
                        echo $_SESSION['message'][0];
                }
                else
                    echo 'POST not good';
            }
            else 
                echo 'NOT a POST';   
        }
        
        public function forgot(){
            if(isset($_POST)){
                if(isset($_POST['email'])){
                    $email = $_POST['email'];
                    $this->load->model('Main_model');
                    $check_email_exist = $this->Main_model->check_valid_user($email);
                    if($check_email_exist){
                        echo 'The new password was sent to your email !';
                    }
                    else{
                        echo 'Not existing user !';
                    }
                }
            }
        }
        
        function validate($what, $value){
            if(!isset($_SESSION['message']))
                $_SESSION['message'] = '';

            switch ($what){
                case 'name' :
                    if((strlen($value) < 50) and (strlen($value) > 2))
                        return true;
                    else{
                        $_SESSION['message'][0] = 'First name must be less than 50 chars !';
                        return false;
                    }
                break;        
                case 'email' :
                    $validate = preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $value);
                    if($validate)
                        return true;
                    else{
                        $_SESSION['message'][1] = 'Not a valid email !';
                        return false;
                    }
                break;    
                case 'password' :
                    $value = trim($value);
                    $tmp = explode(' ', $value);
                    if(is_array($tmp) and (strlen($value) < 6)){
                        $_SESSION['message'][2] = 'Password must have more than 5 chars !';
                        return false;
                    }
                    else
                        return true;
                 break;   
            } 
        }
        
        public function generate_guid($num_of_chars){
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            $size = strlen($chars);
            $gen_txt = '';
            for($i=0;$i<$num_of_chars;$i++){
                $gen_txt .= $chars[rand(0, $size-1)];
            }
            return $gen_txt;  
        }
        
        public function get_script_code($api_key){
            $script = '<script type=text/javascript">
            (function () { 
                var scriptProto = "https:" == document.location.protocol ? "https://" : "http://"; 
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.async = true;
                script.src = scriptProto+"scrape.mk/v1/js?api_key=' . $api_key . '&site="+document.domain+\'\';
                (document.getElementsByTagName(\'head\')[0] || document.body).appendChild(script);
                })();
            </script>';
            
            return $script;
        }
        
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */